package com.zx.sercurity;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
 * 第三方证书风险
 */
public class CustomCertificatesRisk implements RiskControlInterface<RiskResult.CustomCertificatesRiskResult> {
    @Override
    public RiskResult.CustomCertificatesRiskResult riskCheck(Context context) {
        List<String> certificatesData = hasCustomCertificates();
        if (!certificatesData.isEmpty()) {
            return new RiskResult.CustomCertificatesRiskResult(certificatesData);
        } else {
            return new RiskResult.CustomCertificatesRiskResult(false);
        }
    }


    public List<String> hasCustomCertificates() {
        //File systemCertsDir = new File("/system/etc/security/cacerts/");
        File userCertsDir = new File("/data/misc/user/0/cacerts-added/");

        List<String> certificatesData = new ArrayList<>();
        // 检查用户证书目录是否存在
        if (userCertsDir.exists() && userCertsDir.listFiles() != null) {
            for (File listFiles : userCertsDir.listFiles()) {
                try {
                    // 从文件加载证书
                    FileInputStream fis = new FileInputStream(listFiles.getAbsolutePath());
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
                    String sb = "";
                    // 获取证书序列号
                    String serialNumber = cert.getSerialNumber().toString(16);
                    sb += "证书序列号: " + serialNumber;

                    // 获取证书主体信息(包含组织和单位)
                    String subject = cert.getSubjectX500Principal().getName();
                    sb += "；证书主体: " + subject;

                    // 从主体信息中提取组织(O)和组织单位(OU)
                    String[] subjectArray = subject.split(",");
                    for (String item : subjectArray) {
                        if (item.startsWith("O=")) {
                            sb += "；组织: " + item.substring(2);
                        }
                        if (item.startsWith("OU=")) {
                            sb += "；组织单位: " + item.substring(3);
                        }
                    }
                    certificatesData.add(sb);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return certificatesData;
    }
}
